using B.S.Data.MES.API.Applications.CangKu.Command;
using B.S.Domain.CangKu;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;

namespace B.S.Data.MES.API.Applications.CangKu.CommandHandlers
{
    /// <summary>
    /// 获取所有成品列表命令处理程序
    /// 实现获取所有成品数据的逻辑，用于下拉框绑定
    /// </summary>
    public class GetAllFinishedProductsCommandHandler : IRequestHandler<GetAllFinishedProductsCommand, APIRequst<List<Finished_ProductTest>>>
    {
        private readonly IBaseRepository<Finished_ProductTest> finishedProductRepository;

        /// <summary>
        /// 构造函数，注入仓储依赖
        /// </summary>
        /// <param name="finishedProductRepository">成品检验仓储</param>
        public GetAllFinishedProductsCommandHandler(IBaseRepository<Finished_ProductTest> finishedProductRepository)
        {
            this.finishedProductRepository = finishedProductRepository;
        }

        /// <summary>
        /// 处理获取所有成品列表的请求
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含成品列表的API响应</returns>
        public async Task<APIRequst<List<Finished_ProductTest>>> Handle(GetAllFinishedProductsCommand request, CancellationToken cancellationToken)
        {
            // 创建API响应对象
            APIRequst<List<Finished_ProductTest>> response = new APIRequst<List<Finished_ProductTest>>();
            
            // 设置响应状态为成功
            response.Code = RequstCode.成功;
            response.Msg = RequstCode.成功.ToString();
            
            // 查询所有成品数据，不进行分页
            // 按照ProductName排序，方便用户在下拉框中查找
            var finishedProducts = finishedProductRepository.GetAll()
                .OrderBy(x => x.ProductName)
                .ToList();
            
            // 设置响应数据
            response.Data = finishedProducts;
            
            // 返回响应结果
            return await Task.FromResult(response);
        }
    }
}